package com.bauer.java;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;



public class HebaoFileAesHelper
{

    private static final String CHARSET= "UTF-8";

    public static final String aes_key_algorithm = "AES";

    public static final String cipher_algorithm = "AES/ECB/PKCS5Padding";

    private SecretKeySpec keySpec = null;

    public HebaoFileAesHelper(String key){
        keySpec = new SecretKeySpec(key.getBytes(), "AES");
    }

    public byte[] encrypt(byte[] content) throws NoSuchAlgorithmException {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(1, keySpec);
            return cipher.doFinal(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public String decrypt(String hexString) {
        try {
            if(StringUtils.isEmpty(hexString)) {
                return "";
            }
            String result = "";
            byte[] enBytes = parseHexStr2Byte(String.valueOf(result) + hexString);
            byte[] plainBytes= decrypt(enBytes);
            result = new String(plainBytes, CHARSET);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     *
     * @param filePath
     * @return true=明文，false=密文
     */
    public boolean isPlainFile(String firstLine){
        if(firstLine.contains("|")) {
            return true;
        }
        return false;
    }


    public byte[] decrypt(byte[] content) throws NoSuchAlgorithmException {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, keySpec);
            return cipher.doFinal(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 重载，解密字符串，使用配置的编码
     * @param encryStr
     * @return
     */
    public String encrypt(String encryStr) {
        try {
            byte[] plainBytes= this.encrypt(encryStr.getBytes(CHARSET));
            return parseByte2HexStr(plainBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 字节转换字符串
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = String.valueOf('0') + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 字符串转字节
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 文件加密
     *
     * @param file1
     * @param file2
     * @return
     */
    public String encryptHand(File file1, File file2) {
        String result = "";
        String line = "";

        String encryptResultStr = "";
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file1), CHARSET));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2), CHARSET));
            while ((line = br.readLine()) != null) {
                String encryptStr= String.valueOf(result) + line;
                byte[] bt = encrypt(encryptStr.getBytes(CHARSET));
                encryptResultStr = parseByte2HexStr(bt);
                bw.write(encryptResultStr);
                bw.newLine();
            }
            bw.flush();
            bw.close();
            br.close();
        }  catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(bw);
            IOUtils.closeQuietly(br);
        }
        return result;
    }

    /**
     * 文件解密
     *
     * @param file1
     * @param file2
     */
    public void decryptHand(File file1, File file2) {
        String line = "";
        byte[] decryptFrom = null;
        byte[] decryptResult = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file1), CHARSET));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2), CHARSET));
            while ((line = br.readLine()) != null) {

                String result = "";
                decryptFrom = parseHexStr2Byte(String.valueOf(result) + line);
                decryptResult = decrypt(decryptFrom);
                result = new String(decryptResult, CHARSET);
                bw.write(result);
                bw.newLine();
            }
            bw.flush();
            bw.close();
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(bw);
            IOUtils.closeQuietly(br);
        }
    }
}

